package com.atguigu.crowd.until;

import com.atguigu.crowd.constant.CrowdConstant;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;


/**
 * 爱众筹项目通用的工具方法类
 * @author Jie
 */
public class CrowdUtil {

    /**
     * 此方法是对明文字符串进行MD5加密
     * @param source 明文字符串
     * @return 加密的结果
     */
    public static String md5(String source){

        // 判断传过来的参数是否为有效字符串
        if( source == null || source.length() == 0){
            // 如果不是则直接抛出异常
            throw new RuntimeException(CrowdConstant.MESSAGE_STRING_INVALIDATE);
        }

        try {
            String algorithm = "md5";
            //获取MessageDigest对象
            MessageDigest instance = MessageDigest.getInstance(algorithm);
            //将明文字符串转换为对应的字节数组
            byte[] bytes = source.getBytes();
            // 执行加密
            byte[] digest = instance.digest(bytes);
            //创建BigInteger
            int signum = 1;
            BigInteger bigInteger = new BigInteger(signum, digest);
            //按照十六进制将BigInteger转换为字符串
            int radix = 16;
            String encoded = bigInteger.toString(radix).toUpperCase();
            return encoded;

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 判断当前请求是否为ajax请求
     * @param request
     * @return
     *  true：表示为ajax请求
     *  false：表示为普通请求
     */
    public static boolean judgeRequestType(HttpServletRequest request){
        //获取请求头信息
        String accept = request.getHeader("Accept");
        String header = request.getHeader("X-Requested-With");

        return (accept != null && accept.contains("application/json"))
                ||
                (header !=null && header.equals("XMLHttpRequest"));

    }

}
